<template>
  <div>
    <n-form ref="formRef" :model="modelRef" :rules="rules">
      <n-form-item path="age" label="年龄">
        <n-input v-model:value="modelRef.age" @keydown.enter.prevent />
      </n-form-item>
      <n-form-item path="password" label="密码">
        <n-input
          v-model:value="modelRef.password"
          type="password"
          @keydown.enter.prevent
        />
      </n-form-item>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { FormInst, FormItemInst, FormItemRule, useMessage, FormRules } from "naive-ui";

interface ModelType {
  age: string | null;
  password: string | null;
  reenteredPassword: string | null;
}

const formRef = ref<FormInst | null>(null);
const message = useMessage();
const modelRef = ref<ModelType>({
  age: null,
  password: null,
  reenteredPassword: null,
});

const rules: FormRules = {
  age: [
    {
      required: true,
      validator(rule: FormItemRule, value: string) {
        if (!value) {
          return new Error("需要年龄");
        } else if (!/^\d*$/.test(value)) {
          return new Error("年龄应该为整数");
        } else if (Number(value) < 18) {
          return new Error("年龄应该超过十八岁");
        }
        return true;
      },
      trigger: ["input", "blur"],
    },
  ],
  password: [
    {
      required: true,
      validator(rule: FormItemRule, value: string) {
        if (!value) {
          return new Error("请输入密码");
        }
        return true;
      },
      trigger: ["input", "blur"],
    },
  ],
};

watch(modelRef.value, (newVal) => {
  console.log(newVal, "变化了");
});
</script>
